<template>
  <div class="user-list">
    <div class="page-header">
      <div class="header-content">
        <h1>用户管理</h1>
        <p class="subtitle">管理系统用户信息、角色分配和权限控制</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd" class="action-btn">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
        <el-button @click="handleImport" class="action-btn">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-header">
        <el-icon><Search /></el-icon>
        <span>搜索筛选</span>
      </div>
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="用户名" class="form-item">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="真实姓名" class="form-item">
          <el-input 
            v-model="searchForm.realName" 
            placeholder="请输入真实姓名"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="角色" class="form-item">
          <el-select v-model="searchForm.roleId" placeholder="请选择角色" clearable class="search-select">
            <el-option 
              v-for="role in roleOptions" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" class="form-item">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="search-select">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-info">
          <span class="info-text">共 {{ filteredUserList.length }} 条用户</span>
          <span v-if="selectedUsers.length > 0" class="selected-info">
            已选择 {{ selectedUsers.length }} 项
          </span>
        </div>
        <div class="table-actions">
          <el-button size="small" :disabled="selectedUsers.length === 0" @click="handleBatchDelete">
            批量删除
          </el-button>
          <el-button size="small" :disabled="selectedUsers.length === 0" @click="handleBatchStatus">
            批量状态
          </el-button>
        </div>
      </div>
      
      <div v-if="error" class="error-message">
        <el-icon><Warning /></el-icon>
        <span>{{ error }}</span>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-loading-spinner type="circle" size="large"></el-loading-spinner>
        <p>正在加载用户数据...</p>
      </div>
      
      <el-table 
        v-if="dataLoadSuccess" 
        :data="displayUserList" 
        class="user-table"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center">
          <template #default="scope">
            <span class="index-text">{{ (pagination.current - 1) * pagination.size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="用户ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column label="角色" width="120" align="center">
          <template #default="scope">
            <el-tag 
              v-for="role in scope.row.roles" 
              :key="role.id"
              :type="getRoleTagType(role.name)"
              size="small"
              class="role-tag"
            >
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'" size="small">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="160" align="center">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.lastLoginTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="handleAssignRole(scope.row)">分配角色</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === '1' ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === '1' ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredUserList.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认密码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="role-assignment">
        <p class="assignment-info">为用户 <strong>{{ currentUser?.username }}</strong> 分配角色：</p>
        <el-checkbox-group v-model="selectedRoles" class="role-checkbox-group">
          <el-checkbox 
            v-for="role in roleOptions" 
            :key="role.id" 
            :label="role.id"
            class="role-checkbox"
          >
            {{ role.name }}
            <span class="role-description">{{ role.description }}</span>
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRoleSubmit" :loading="roleSubmitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'
import { Plus, Search, Upload, Warning } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

export default defineComponent({
  name: 'UserList',
  components: {
    Plus,
    Search,
    Upload,
    Warning
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const error = ref('')
    const dataLoadSuccess = ref(false)
    const dialogVisible = ref(false)
    const roleDialogVisible = ref(false)
    const isEdit = ref(false)
    const submitLoading = ref(false)
    const roleSubmitLoading = ref(false)
    const selectedUsers = ref([])
    const currentUser = ref(null)
    const selectedRoles = ref([])
    const userFormRef = ref(null)

    // 用户列表数据
    const userList = ref([])
    const roleOptions = ref([])

    // 搜索表单
    const searchForm = reactive({
      username: '',
      realName: '',
      roleId: '',
      status: ''
    })

    // 用户表单
    const userForm = reactive({
      id: '',
      username: '',
      realName: '',
      email: '',
      phone: '',
      password: '',
      confirmPassword: '',
      status: '1',
      remark: ''
    })

    // 分页配置
    const pagination = reactive({
      current: 1,
      size: 20
    })

    // 表单验证规则
    const userFormRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== userForm.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 计算属性
    const filteredUserList = computed(() => {
      let filtered = userList.value

      if (searchForm.username) {
        filtered = filtered.filter(user => 
          user.username.toLowerCase().includes(searchForm.username.toLowerCase())
        )
      }

      if (searchForm.realName) {
        filtered = filtered.filter(user => 
          user.realName.includes(searchForm.realName)
        )
      }

      if (searchForm.roleId) {
        filtered = filtered.filter(user => 
          user.roles.some(role => role.id === searchForm.roleId)
        )
      }

      if (searchForm.status !== '') {
        filtered = filtered.filter(user => user.status === searchForm.status)
      }

      return filtered
    })

    const displayUserList = computed(() => {
      const start = (pagination.current - 1) * pagination.size
      const end = start + pagination.size
      return filteredUserList.value.slice(start, end)
    })

    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑用户' : '新增用户'
    })

    // 方法
    const loadUserList = async () => {
      loading.value = true
      error.value = ''
      
      try {
        const response = await request.get('/users')
        userList.value = response.data || []
        dataLoadSuccess.value = true
      } catch (err) {
        error.value = '加载用户数据失败'
        console.error('Load user list error:', err)
      } finally {
        loading.value = false
      }
    }

    const loadRoleOptions = async () => {
      try {
        const response = await request.get('/roles')
        roleOptions.value = response.data || []
      } catch (err) {
        console.error('Load role options error:', err)
      }
    }

    const handleSearch = () => {
      pagination.current = 1
    }

    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.current = 1
    }

    const handleAdd = () => {
      isEdit.value = false
      resetUserForm()
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      isEdit.value = true
      Object.assign(userForm, row)
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${row.username}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await request.delete(`/users/${row.id}`)
        ElMessage.success('删除成功')
        loadUserList()
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const handleToggleStatus = async (row) => {
      try {
        const newStatus = row.status === '1' ? '0' : '1'
        const statusText = newStatus === '1' ? '启用' : '禁用'
        
        await ElMessageBox.confirm(
          `确定要${statusText}用户 "${row.username}" 吗？`,
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await request.put(`/users/${row.id}/status`, { status: newStatus })
        ElMessage.success(`${statusText}成功`)
        loadUserList()
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }

    const handleAssignRole = (row) => {
      currentUser.value = row
      selectedRoles.value = row.roles.map(role => role.id)
      roleDialogVisible.value = true
    }

    const handleRoleSubmit = async () => {
      roleSubmitLoading.value = true
      
      try {
        await request.put(`/users/${currentUser.value.id}/roles`, {
          roleIds: selectedRoles.value
        })
        ElMessage.success('角色分配成功')
        roleDialogVisible.value = false
        loadUserList()
      } catch (err) {
        ElMessage.error('角色分配失败')
      } finally {
        roleSubmitLoading.value = false
      }
    }

    const handleSubmit = async () => {
      if (!userFormRef.value) return
      
      try {
        await userFormRef.value.validate()
        submitLoading.value = true

        if (isEdit.value) {
          await request.put(`/users/${userForm.id}`, userForm)
          ElMessage.success('更新成功')
        } else {
          await request.post('/users', userForm)
          ElMessage.success('创建成功')
        }

        dialogVisible.value = false
        loadUserList()
      } catch (err) {
        if (err !== false) {
          ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
        }
      } finally {
        submitLoading.value = false
      }
    }

    const handleDialogClose = () => {
      resetUserForm()
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
    }

    const resetUserForm = () => {
      Object.assign(userForm, {
        id: '',
        username: '',
        realName: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: '',
        status: '1',
        remark: ''
      })
    }

    const handleSelectionChange = (selection) => {
      selectedUsers.value = selection
    }

    const handleBatchDelete = async () => {
      if (selectedUsers.value.length === 0) return

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const ids = selectedUsers.value.map(user => user.id)
        await request.delete('/users/batch', { data: { ids } })
        ElMessage.success('批量删除成功')
        loadUserList()
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }

    const handleBatchStatus = async () => {
      if (selectedUsers.value.length === 0) return

      try {
        const { value: status } = await ElMessageBox.prompt(
          '请输入状态值 (1: 启用, 0: 禁用)',
          '批量设置状态',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[01]$/,
            inputErrorMessage: '请输入 0 或 1'
          }
        )

        const ids = selectedUsers.value.map(user => user.id)
        await request.put('/users/batch/status', { ids, status })
        ElMessage.success('批量设置成功')
        loadUserList()
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('批量设置失败')
        }
      }
    }

    const handleImport = () => {
      ElMessage.info('批量导入功能开发中...')
    }

    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
    }

    const handleCurrentChange = (current) => {
      pagination.current = current
    }

    const getRoleTagType = (roleName) => {
      const typeMap = {
        'admin': 'danger',
        'manager': 'warning',
        'user': 'info'
      }
      return typeMap[roleName] || 'info'
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
    }

    // 生命周期
    onMounted(() => {
      loadUserList()
      loadRoleOptions()
    })

    return {
      loading,
      error,
      dataLoadSuccess,
      dialogVisible,
      roleDialogVisible,
      isEdit,
      submitLoading,
      roleSubmitLoading,
      selectedUsers,
      currentUser,
      selectedRoles,
      userFormRef,
      userList,
      roleOptions,
      searchForm,
      userForm,
      userFormRules,
      pagination,
      filteredUserList,
      displayUserList,
      dialogTitle,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleDelete,
      handleToggleStatus,
      handleAssignRole,
      handleRoleSubmit,
      handleSubmit,
      handleDialogClose,
      handleSelectionChange,
      handleBatchDelete,
      handleBatchStatus,
      handleImport,
      handleSizeChange,
      handleCurrentChange,
      getRoleTagType,
      formatDateTime
    }
  }
})
</script>

<style lang="scss" scoped>
@use '../../styles/variables.scss' as *;
@use '../../styles/responsive.scss' as *;
@use '../../styles/common.scss' as *;

.user-list {
  padding: 20px;
  
  @include respond-to(xs) {
    padding: 12px;
  }
}

.page-header {
  @include flex-between;
  margin-bottom: 20px;
  
  @include respond-to(xs) {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .header-content {
    h1 {
      margin: 0 0 4px 0;
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
    }
    
    .subtitle {
      margin: 0;
      color: var(--text-color-secondary);
      font-size: 14px;
    }
  }
  
  .header-actions {
    @include flex-center;
    gap: 8px;
    
    .action-btn {
      @include flex-center;
      gap: 4px;
    }
  }
}

.search-card {
  margin-bottom: 20px;
  
  .search-header {
    @include flex-center;
    gap: 8px;
    margin-bottom: 16px;
    font-weight: 500;
    color: var(--text-color-primary);
  }
  
  .search-form {
    .form-item {
      margin-bottom: 12px;
      
      .search-input,
      .search-select {
        width: 200px;
        
        @include respond-to(xs) {
          width: 100%;
        }
      }
    }
    
    .search-btn,
    .reset-btn {
      @include flex-center;
      gap: 4px;
    }
  }
}

.table-card {
  .table-header {
    @include flex-between;
    margin-bottom: 16px;
    
    .table-info {
      @include flex-center;
      gap: 12px;
      
      .info-text {
        color: var(--text-color-secondary);
        font-size: 14px;
      }
      
      .selected-info {
        color: var(--primary-color);
        font-size: 14px;
        font-weight: 500;
      }
    }
  }
  
  .error-message {
    @include flex-center;
    gap: 8px;
    padding: 20px;
    color: var(--danger-color);
    background: var(--danger-bg);
    border-radius: 4px;
    margin-bottom: 16px;
  }
  
  .loading-container {
    @include flex-center;
    flex-direction: column;
    gap: 12px;
    padding: 40px;
    color: var(--text-color-secondary);
  }
}

.user-table {
  .index-text {
    color: var(--text-color-secondary);
    font-size: 13px;
  }
  
  .role-tag {
    margin-right: 4px;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

.pagination-container {
  @include flex-center;
  margin-top: 20px;
}

.user-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.role-assignment {
  .assignment-info {
    margin-bottom: 16px;
    color: var(--text-color-primary);
  }
  
  .role-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
    
    .role-checkbox {
      display: flex;
      align-items: flex-start;
      gap: 8px;
      
      .role-description {
        color: var(--text-color-secondary);
        font-size: 12px;
        margin-left: 4px;
      }
    }
  }
}
</style> 